﻿Imports Microsoft.VisualBasic
Imports System
Imports System.Xml
Imports System.Xml.Linq
Imports System.Text
Public Class LogWriter

    Shared m_baseDir As String = Environment.CurrentDirectory & "\Log.logx"


    Private Shared Function GetLogFileName(ByVal m_sFileName As String) As String
        Dim sFileName As String
        Dim sExtension As String
        Dim oSB As New StringBuilder
        If (Strings.InStr(m_sFileName, ".", CompareMethod.Binary) > 0) Then
            Dim iPos As Integer = Strings.InStr(m_sFileName, ".", CompareMethod.Binary)
            sExtension = Strings.Mid(m_sFileName, (iPos + 1))
            sFileName = Strings.Mid(m_sFileName, 1, (iPos - 1))
        Else
            sFileName = m_sFileName
            sExtension = ".txt"
        End If

        With oSB
            .Append(sFileName)
            .Append("_")
            .Append(DateAndTime.Now.ToString("yyyy-MM-dd"))
            .Append(".")
            .Append(sExtension)
            Return oSB.ToString
            oSB = Nothing
        End With
    End Function

    Public Shared Sub WriteLog(ByVal message As String)
        'just in case: we protect code with try.
        Try
            Dim filename As String = GetLogFileName(m_baseDir)
            Dim sw As New System.IO.StreamWriter(filename, True)
            Dim xmlEntry As New XElement("logEntry", New XElement("Date", System.DateTime.Now.ToString()), New XElement("Message", message))
            sw.WriteLine(xmlEntry)
            sw.Close()
        Catch generatedExceptionName As Exception
        End Try
    End Sub

    Public Shared Sub WriteLog(ByVal ex As Exception)
        'just in case: we protect code with try.
        Try
            Dim filename As String = GetLogFileName(m_baseDir)
            Dim sw As New System.IO.StreamWriter(filename, True)
            Dim xmlEntry As New XElement("logEntry", New XElement("Date", System.DateTime.Now.ToString()), New XElement("Exception", New XElement("Source", ex.Source), New XElement("Message", ex.Message), New XElement("Stack", ex.StackTrace)))
            'has inner exception?
            If Not ex.InnerException Is Nothing Then
                xmlEntry.Element("Exception").Add(New XElement("InnerException", New XElement("Source", ex.InnerException.Source), New XElement("Message", ex.InnerException.Message), New XElement("Stack", ex.InnerException.StackTrace)))
            End If
            sw.WriteLine(xmlEntry)
            sw.Close()
        Catch generatedExceptionName As Exception
        End Try
    End Sub

End Class
